<template>
  <el-drawer
    :title="title"
    :wrapper-closable="false"
    size="90%"
    :modal="false"
    :visible.sync="showDrawer"
    direction="rtl"
    @close="close"
  >
    <el-row>
      <el-button v-if="selected.length" type="warning" size="mini" @click="generateHtmlTable">生成邮件内容</el-button>
      <el-button v-if="selected.length" type="primary" size="mini" @click="saveAsQuote">批量保存产品</el-button>
      <el-button v-if="selected.length" type="success" :loading="imageProcessing" size="mini" @click="showImageProcessDialog">图片处理</el-button>
      <el-button v-if="selectedRows.length > 0" type="danger" size="mini" @click="handleBatchRemove">批量移除({{ selectedRows.length }})</el-button>
      <a v-if="quote" :href="quote.quote_domain + quote.token" title="打开报价单" target="_blank">{{ quote.name }}</a>
      <el-button size="mini" type="primary" style="float: right;margin-right: 30px" @click="addRow">添加行</el-button>
      <image-upload-dialog
        :action="uploadUrl"
        :data="uploadData"
        style="float: right;margin-right: 10px"
        @on-batch-insert="handleBatchInsert"
      />
      <el-button size="mini" :loading="fetchloading" type="primary" style="float: right;margin-right: 10px" @click="addByUrl">网页图片提取</el-button>
    </el-row>
    <el-divider>目录册参数</el-divider>
    <el-select v-model="temp.category" placeholder="请选择类别" style="width: 120px; margin-left: 20px">
      <el-option value="" label="全部" />
      <el-option v-for="item in categorys" :key="item.value" :label="item.label" :value="item.value" />
    </el-select>
    报价单英文标题:<el-input v-model="temp.name" size="mini" placeholder="输入英文给客户看" clearable style="width: 300px; display: inline-block;" />
    备注:<el-input v-model="temp.note" size="mini" placeholder="输入中文备注方便自己查找" clearable style="width: 300px; display: inline-block;" />
    电话:<el-input v-model="temp.phone" size="mini" placeholder="输入电话" clearable style="width: 200px; display: inline-block;" />
    邮箱:<el-input v-model="temp.email" size="mini" placeholder="输入邮箱" clearable style="width: 200px; display: inline-block;" />
    <span style="margin-left: 10px" />
    <el-switch
      v-model="temp.show_price"
      active-color="#13ce66"
      active-text="显示报价"
      inactive-text="隐藏报价"
      inactive-color="#ff4949"
    />
    <el-switch
      v-model="temp.show_moq"
      active-text="显示起订量"
      inactive-text="隐藏起订量"
      active-color="#13ce66"
      inactive-color="#ff4949"
    />
    <el-button type="primary" size="mini" @click="modifyQuote">保存参数</el-button>
    <el-table
      ref="dragTable"
      :data="selected"
      border
      fit
      highlight-current-row
      :default-sort="{prop: 'position', order: 'ascending'}"
      @selection-change="handleSelectionChange"
    >
      style="width: 100%; margin-top: 10px"
      @sort-change="handleSort">
      <el-table-column
        type="selection"
        width="55"
      />
      <el-table-column
        label="位置"
        width="80"
        prop="position"
        sortable
      >
        <template slot-scope="scope">
          <el-input
            v-model.number="scope.row.position"
            size="mini"
            type="number"
            @change="handleModifyPosition(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="images" label="产品图片" width="180">
        <template slot-scope="scope">
          <div v-for="(image, index) in scope.row.images" :key="index" class="image-item">
            <el-image
              style="width: 100px; height: auto; margin-right: 10px"
              :src="image"
              :preview-src-list="[image]"
            />
            <span @click="removeImage(scope.row, index)"><i class="el-icon-delete" /></span>
            <span style="margin-left: 5px; cursor: pointer;" title="AI生成图片描述" @click="handleAiGenerateImageDescription(scope.row, image)">
              <i class="el-icon-magic-stick" style="color: #1EB7E6;" />
            </span>
          </div>
          <crmcommonfilesmanager :urllist="scope.row.images" color="#1890ff" class="editor-upload-btn" />
        </template>
      </el-table-column>
      <el-table-column prop="sku" label="sku" width="180">
        <template slot-scope="scope">
          <el-input v-model="scope.row.sku" size="mini" />
        </template>
      </el-table-column>
      <el-table-column prop="parameters" label="参数" width="400">
        <template slot-scope="scope">
          <el-tabs v-model="scope.row.activeName" tab-position="left" @change="handleChangeParames(row)">
            <el-tab-pane label="中文" name="first">
              <el-input v-model="scope.row.parameters" type="textarea" :rows="3" size="mini" />
              <div style="margin-top: 5px;">
                <el-button
                  size="mini"
                  type="primary"
                  :loading="scope.row.aiExtracting"
                  @click="handleAiExtractParameters(scope.row, 'zh')"
                >
                  <i class="el-icon-cpu" /> AI提取参数
                </el-button>
              </div>
            </el-tab-pane>
            <el-tab-pane label="英文" name="second">
              <el-input v-model="scope.row.parameters_en" type="textarea" :rows="3" size="mini" />
              <div style="margin-top: 5px;">
                <el-button size="mini" @click="handleTranslate(scope.row)">翻译中文</el-button>
                <el-button
                  size="mini"
                  type="primary"
                  :loading="scope.row.aiExtracting"
                  style="margin-left: 5px;"
                  @click="handleAiExtractParameters(scope.row, 'en')"
                >
                  <i class="el-icon-cpu" /> AI提取参数
                </el-button>
              </div>
            </el-tab-pane>
          </el-tabs>
        </template>
      </el-table-column>
      <el-table-column prop="moq" label="moq/price" width="180">
        <template slot-scope="scope">
          MOQ:<el-input v-model="scope.row.moq" size="mini" /><br>
          price:<el-input v-model="scope.row.price" size="mini" style="display: inline-block;width: 100px" />
          <el-input v-model="scope.row.currency" size="mini" style="display: inline-block;width: 60px" />
        </template>
      </el-table-column>
      <el-table-column prop="note" label="note" width="200">
        <template slot-scope="scope">
          <el-input v-model="scope.row.note" type="textarea" :rows="3" size="mini" />
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button v-if="scope.row.id" size="mini" type="warning" @click="handleEditRow(scope.row)">修改</el-button>
          <el-button v-else size="mini" type="primary" @click="handleAddNewProduct">添加</el-button>
          <el-button v-if="scope.row.id" size="mini" type="danger" @click="handleDeleteFromList(scope.row)">删除</el-button>
          <el-button v-else size="mini" type="danger" @click="handleRemoveFromList(scope.row)">移除</el-button>
        </template>
      </el-table-column>

    </el-table>

    <!-- 图片处理对话框 -->
    <el-dialog
      title="图片处理设置"
      :visible.sync="imageProcessDialogVisible"
      append-to-body
      width="500px"
      @close="handleCloseImageProcessDialog"
    >
      <el-form :model="imageProcessForm" label-width="120px">
        <el-form-item label="处理方式">
          <el-checkbox v-model="imageProcessForm.remove_bg">抠图去背景</el-checkbox>
          <el-checkbox v-model="imageProcessForm.remove_watermark">去水印</el-checkbox>
          <el-checkbox v-model="imageProcessForm.add_watermark">添加水印</el-checkbox>
        </el-form-item>

        <el-form-item label="处理范围">
          <el-radio-group v-model="imageProcessForm.process_type">
            <el-radio label="selected">仅处理选中产品</el-radio>
            <el-radio label="all">处理整个报价单所有产品</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item v-if="imageProcessForm.remove_watermark" label="去水印蒙版">
          <el-upload
            class="upload-demo"
            action=""
            :before-upload="handleWatermarkMaskUpload"
            :show-file-list="false"
            accept="image/*"
          >
            <el-button size="small" type="primary">上传蒙版图片</el-button>
            <div slot="tip" class="el-upload__tip">支持jpg/png格式图片，用于标识水印位置</div>
          </el-upload>
          <div v-if="imageProcessForm.watermark_mask">
            <img :src="watermarkMaskPreview" style="max-width: 200px; max-height: 100px; margin-top: 10px">
          </div>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="imageProcessDialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="imageProcessing" @click="handleImageProcess">开始处理</el-button>
      </div>
    </el-dialog>

    <!-- AI生成图片描述组件 -->
    <AITask
      ref="aiTaskComponent"
      :params="aiTaskParams"
      task-name="ai_generate_product_description"
      show-name="AI生成产品描述"
      button-text="AI生成描述"
      :show-apply-button="true"
      :show-icon="false"
      @apply="handleApplyAiResult"
    />
  </el-drawer>
</template>

<script>
import { Post, Put, Get } from '@/api/crm/crmquote'
import { Post as AddProduct, ProcessImages } from '@/api/crm/crmquoteproduct'
import { Delete, Put as ModifyQuoteProduct } from '@/api/crm/crmm'
import Crmcommonfilesmanager from './crmCommonfilesmanager'
import { Get as GetCustomer } from '@/api/crm/crmcustomer'
import { FetchImages } from '@/api/crm/crmapi'
import { Translate } from '@/api/crm/crmmanage'
import { Post as GetAiContent } from '@/api/cms/openai'
import qs from 'qs'
import ImageUploader from './imageuploader'
import ImageUploadDialog from './imageuploader'
import Sortable from 'sortablejs'
import AITask from '@/components/AITask'

export default {
  name: 'Crmquoteproduct',
  components: { ImageUploadDialog, ImageUploader, Crmcommonfilesmanager, AITask },
  props: {
    // 传入的已选产品列表
    selectedProducts: {
      type: Array,
      default: () => [], // 默认为空数组
      required: true
    },
    // 控制 Drawer 显示的状态
    visible: {
      type: Boolean,
      default: false
    },
    isNew: {
      type: Boolean,
      default: false
    },
    // ID
    quote: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      sortable: null, // 用于存储 Sortable 实例
      title: '目录册产品',
      quote_id: '',
      uploadUrl: process.env.VUE_APP_BASE_API + '/crm/api/crmfile/',
      uploadData: {
        directory_name: 'quoteproductimages',
        acl_type: 'public_read'
      },
      categorys: [
        {
          label: '跑步',
          value: 'running'
        },
        {
          label: '健身',
          value: 'fitness'
        },
        {
          label: '瑜伽',
          value: 'yoga'
        },
        {
          label: '骑行',
          value: 'cycling'
        },
        {
          label: '钓鱼',
          value: 'fishing'
        },
        {
          label: '马术',
          value: 'equestrian'
        },
        {
          label: '篮球',
          value: 'basketball'
        },
        {
          label: '足球',
          value: 'football'
        },
        {
          label: '羽毛球',
          value: 'badminton'
        },
        {
          label: '游泳',
          value: 'swimming'
        },
        {
          label: '户外',
          value: 'outdoor'
        },
        {
          label: '其他',
          value: 'other'
        }
      ],
      fetchloading: false,
      temp: {
        name: '',
        note: '',
        phone: '8618162768130',
        email: 'sales@berunwear.com',
        category: '',
        crmcustomer_id: '',
        show_price: false,
        show_moq: false,
        products: []
      },

      selected: [],
      showDrawer: false,
      current_row: {
        images: []
      },
      options: [],
      loading: false,
      imageProcessing: false,
      imageProcessDialogVisible: false,
      imageProcessForm: {
        remove_bg: true,
        remove_watermark: false,
        add_watermark: true,
        process_type: 'all',
        watermark_mask: null,
        watermark_mask_url: null
      },
      watermarkMaskPreview: null,
      selectedRows: [],
      aiTaskParams: {},
      currentAiRow: null
    }
  },
  watch: {
    visible(val) {
      if (val) {
        // 如果 Drawer 显示时，需要做一些初始化操作
        if (this.selectedProducts && this.selectedProducts.length) {
          this.selected = []
        }
        this.selectedProducts.forEach(item => {
          if (!this.selected.some(i => i.sku === item.sku)) {
            item.activeName = 'first'
            this.selected.push(item)
          }
        })
        if (this.quote) {
          this.temp = { ...this.quote }
          this.quote_id = this.quote.id
          this.title = '修改目录册ID:' + this.quote.id + '产品列表'
        }
        if (this.isNew) {
          this.quote_id = null
          this.temp = {
            name: '',
            category: '',
            show_price: false,
            show_moq: false,
            crmcustomer_id: '',
            products: []
          }
          this.title = '新增目录册'
          this.selected = []
        }
        // 新增 position 初始化逻辑
        this.selected.forEach((item, index) => {
          if (item.position === 0 || typeof item.position === 'undefined') {
            this.$set(item, 'position', index + 1)
          }
          // 初始化AI提取状态
          if (typeof item.aiExtracting === 'undefined') {
            this.$set(item, 'aiExtracting', false)
          }
        })
        // this.$nextTick(() => {
        //   this.initializeSortable();
        // });
      }
      this.showDrawer = val
    }
  },
  methods: {
    // 当设置了positon参数后，把全部数据都改动positoin编号，比如把某个改为2，则要全部positon需要变动
    handleModifyPosition(row) {
      const oldPosition = row.position // 获取旧值
      const newPosition = parseInt(row.position) // 从绑定值中获取新位置

      // 有效性校验（确保在数组范围内）
      if (isNaN(newPosition) || newPosition < 1 || newPosition > this.selected.length) {
        this.$nextTick(() => (row.position = oldPosition)) // 回滚无效输入
        return
      }

      // 创建新数组避免直接修改原始数据
      const tempArray = [...this.selected]

      // 找到并移除当前行
      const currentIndex = tempArray.findIndex(item => item.id === row.id)
      const [movedItem] = tempArray.splice(currentIndex, 1)

      // 插入到新位置（数组索引从0开始，position从1开始）
      const targetIndex = newPosition - 1
      tempArray.splice(targetIndex, 0, movedItem)

      // 重新计算所有行的 position
      const sortedData = tempArray.map((item, index) => ({
        ...item,
        position: index + 1
      }))

      // 更新数据（保持响应式）
      this.selected = sortedData
    },
    // 修改后的 initializeSortable 方法
    initializeSortable() {
      this.$nextTick(() => {
        const table = this.$refs.dragTable
        if (!table) return

        const tableBody = table.$el.querySelector('.el-table__body-wrapper tbody') // 精确到 tbody
        if (tableBody) {
          this.sortable = Sortable.create(tableBody, {
            handle: '.drag-handler',
            animation: 150,
            filter: '.el-table__row--static', // 过滤掉不需要拖动的元素
            onEnd: (evt) => {
              const oldIndex = evt.oldIndex
              const newIndex = evt.newIndex
              const movedItem = this.selected[oldIndex]

              // Vue 的数组更新检测
              this.$set(this.selected, newIndex, movedItem)
              this.selected.splice(oldIndex, 1)
            }
          })
        }
      })
    },
    // 拖拽结束时的回调
    onDragEnd(evt) {
      const movedItem = this.selected.splice(evt.oldIndex, 1)[0] // 移动的项
      this.selected.splice(evt.newIndex, 0, movedItem) // 将项插入到新的位置
    },
    handleBatchInsert(newProducts) {
      // 将新产品添加到已选列表
      this.selected.unshift(...newProducts)
    },
    handleUploadSuccess({ file, urls }) {
      console.log('上传成功的文件:', file)
      console.log('所有上传成功的URL列表:', urls)
    },
    handleGetQuoteProduct() {
      Get(this.quote_id, qs.stringify({ get_products: true })).then(res => {
        this.selected = res.data.products
      })
    },
    addByUrl() {
      this.$prompt('请输入网页地址', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^https?:\/\/.+/,
        inputErrorMessage: '请输入以 http:// 或 https:// 开头的网址'
      }).then(({ value }) => {
        this.fetchloading = true
        FetchImages({ task: 'from_url', 'url': value }).then(res => {
          // 处理返回的图片数据
          if (res.images && Array.isArray(res.images)) {
            res.images.forEach(imgData => {
              // 为每个图片创建一个新的产品行
              const newProduct = {
                sku: Math.random().toString(36).substr(2, 8), // 生成随机 SKU
                images: [imgData.url], // 只保存图片 URL
                price: 0,
                activeName: 'first',
                currency: 'USD',
                note: imgData.note,
                moq: 100,
                parameters: '',
                parameters_en: '',
                aiExtracting: false
              }
              this.selected.unshift(newProduct)
            })
            this.fetchloading = false
            this.$message.success(`成功添加 ${res.images.length} 个产品`)
          } else {
            this.fetchloading = false
            this.$message.warning('未找到有效的图片')
          }
        }).catch(err => {
          this.fetchloading = false
          this.$message.error('获取图片失败：' + (err.message || '未知错误'))
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        })
      })
    },
    addRow() {
      const inputRow = {
        sku: '',
        position: 1,
        images: [],
        price: 0,
        activeName: 'first',
        currency: 'USD',
        moq: 100,
        parameters: '',
        parameters_en: '',
        aiExtracting: false
      }
      inputRow.sku = Math.random().toString(36).substr(2, 8)
      // 添加到最前面
      this.selected.unshift(inputRow)
      this.handleModifyPosition(inputRow)
    },
    handleInsertFile(item) {
      console.log(item)
      this.current_row.images.push(item.url)
    },
    removeImage(row, index) {
      row.images.splice(index, 1)
    },
    modifyQuote() {
      if (this.quote_id) {
        Put(this.quote_id, { name: this.temp.name, phone: this.temp.phone, email: this.temp.email, note: this.temp.note, category: this.temp.category, show_price: this.temp.show_price, show_moq: this.temp.show_moq }).then(res => {
          if (res.success) {
            this.quote = res.data || this.quote
            this.$message.success('修改成功')
            // 触发父组件更新，确保数据同步
            this.$emit('quote-updated', this.quote)
          } else {
            this.$message.error('修改失败：' + res.msg)
          }
        }).catch(error => {
          this.$message.error('修改失败：' + (error.message || '未知错误'))
        })
      } else {
        this.$message.error('报价单不存在')
      }
    },
    handleAddNewProduct() {
      // 筛选出没有 id 的新产品
      const newProducts = this.selected.filter(product => !product.id)

      if (newProducts.length === 0) {
        this.$message.info('没有需要添加的新产品')
        return
      }

      // 确保存在 quote_id
      if (!this.quote_id) {
        this.$message.error('报价单ID不存在，请先保存报价单')
        return
      }

      // 创建一个Promise数组来存储所有的添加操作
      const addPromises = newProducts.map(product => {
        // 创建新的对象，避免修改原对象
        const newProduct = {
          ...product,
          crmquote_id: this.quote_id
        }

        // 使用 Post (AddProduct) 接口添加新产品
        return AddProduct(newProduct) // 使用 'product' 路径
          .then(res => {
            // 更新原产品数组中的对应项
            const index = this.selected.findIndex(item => item.sku === product.sku)
            if (index !== -1) {
              this.selected[index] = { ...this.selected[index], ...res.data }
            }
            return res
          })
      })

      // 执行所有添加操作
      Promise.all(addPromises)
        .then(() => {
          this.$message.success(`成功添加 ${newProducts.length} 个新产品`)
          // 可选：重新获取产品列表
          this.handleGetQuoteProduct()
        })
        .catch(error => {
          this.$message.error('添加产品失败：' + (error.message || '未知错误'))
        })
    },
    saveAsQuote() {
      if (this.quote_id) {
        Put(this.quote_id, {
          id: this.quote_id,
          products: this.selected
        }).then(res => {
          this.quote = res.data
          this.handleAddNewProduct()
          this.$message.success('保存目录册信息成功,开始保存新产品')
        })
        // 新增产品,this.selected里面没有ID的产品,全部依次增加
      } else {
        // 如果name为空，不允许保存
        if (!this.temp.name) {
          this.$message.error('报价单名称不能为空')
          return
        }
        // 产品列表不能为空
        if (!this.selected.length) {
          this.$message.error('产品列表不能为空')
          return
        }
        this.temp.products = this.selected
        Post(this.temp).then(res => {
          this.$message.success('保存成功')
        })
      }
    },
    generateHtmlTable() {
      // 实现生成 HTML 表格的逻辑或 emit 事件
      this.$emit('generate-table')
    },
    handleSort() {
      // 处理排序逻辑或 emit 事件
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true
        GetCustomer(null, {
          kw: query,
          pagesize: 10,
          page: 1
        }).then(response => {
          this.options = response.data.data.map(v => {
            v.label = v.name
            v.value = v.id
            return v
          })
          this.loading = false
        })
        this.options = []
      } else {
        this.options = []
      }
    },
    handleRemoveFromList(row) {
      this.selected = this.selected.filter(item => item.sku !== row.sku)
    },
    handleChangeParames(row) {
      if (row.parameters_en.length === 0 && row.parameters.length > 0) {
        this.handleTranslate(row)
      }
    },
    handleTranslate(row) {
      Translate({
        text: row.parameters,
        source_language: 'zh',
        target_language: 'en'
      }).then(response => {
        row.parameters_en = response.data
      })
    },
    handleAiExtractParameters(row, language) {
      // 检查是否有参数内容
      const currentContent = language === 'zh' ? row.parameters : row.parameters_en
      if (!currentContent || currentContent.trim().length === 0) {
        this.$message.warning('请先输入产品参数内容，AI将帮助整理和提取结构化参数')
        return
      }

      // 设置加载状态
      this.$set(row, 'aiExtracting', true)

      // 显示处理中的通知
      this.$notify({
        title: '处理中',
        message: 'AI正在分析参数内容并提取结构化信息...',
        type: 'info',
        duration: 0
      })

      // 准备AI请求参数
      const requestData = {
        aiprompt_id: '280',
        prompt: `从以下内容中提取产品参数信息，以结构化的格式输出。

输出格式要求（每行一个参数，使用"参数名：参数值"的格式）：

常见参数包括但不限于：
- 标题：[产品标题/名称]
- 描述：[产品卖点/特点描述]
- 尺码范围：[如 S,M,L,XL]
- 面料/材质：[如 80%锦纶/20%尼龙]
- 面料成分：[详细成分]
- 克重：[面料克重]
- 颜色：[颜色选项，用逗号分隔]
- 功能特点：[产品功能]
- 其他参数：[任何其他相关参数]

要求：
1. 提取所有可识别的产品参数
2. 标题和描述字段必须包含（如果内容中有的话）
3. 每行一个参数，格式为"参数名：参数值"
4. 如果某个参数在内容中找不到，则不输出
5. 不要添加任何解释、说明或额外文字
6. 保持原始语言输出（中文内容输出中文，英文内容输出英文）

内容：
{{content}}`,
        kvs: [
          {
            'content': currentContent
          }
        ],
        engine: 'gpt-4o-mini',
        prompt_name: 'extract_product_parameters',
        humanway: false
      }

      // 调用AI接口
      GetAiContent(requestData)
        .then(response => {
          // 关闭所有通知
          this.$notify.closeAll()

          if (response && response.original_content) {
            // 根据语言更新对应的参数字段
            if (language === 'zh') {
              row.parameters = response.original_content
            } else {
              row.parameters_en = response.original_content
            }

            this.$notify({
              title: '成功',
              message: `AI${language === 'zh' ? '中文' : '英文'}参数提取完成`,
              type: 'success'
            })
          } else {
            this.$notify({
              title: '提取失败',
              message: 'AI未能提取到有效参数，请检查内容格式或手动整理',
              type: 'warning'
            })
          }
        })
        .catch(error => {
          // 关闭所有通知
          this.$notify.closeAll()

          this.$notify({
            title: '错误',
            message: 'AI参数提取失败：' + (error.message || '未知错误'),
            type: 'error'
          })
        })
        .finally(() => {
          // 清除加载状态
          this.$set(row, 'aiExtracting', false)
        })
    },
    handleAiGenerateImageDescription(row, imageUrl) {
      // 保存当前行
      this.currentAiRow = row
      // 设置AI任务参数
      this.aiTaskParams = { image_url: imageUrl }
      // 通过ref调用AITask组件的方法打开对话框
      this.$nextTick(() => {
        if (this.$refs.aiTaskComponent) {
          this.$refs.aiTaskComponent.handleShowDialog()
        }
      })
    },
    handleApplyAiResult(result) {
      // 从FINAL_RESULT标记中提取结果
      const finalResultMatch = result.match(/<!--FINAL_RESULT:\s*(.*?)\s*-->/)
      if (finalResultMatch && this.currentAiRow) {
        // 解析提取的参数文本
        let paramsText = finalResultMatch[1]
        // 将\\n转换为真实的换行符
        paramsText = paramsText.replace(/\\n/g, '\n')

        // 追加到现有参数中（如果有的话）
        if (this.currentAiRow.parameters) {
          this.currentAiRow.parameters += '\n' + paramsText
        } else {
          this.currentAiRow.parameters = paramsText
        }

        this.$notify({
          title: '成功',
          message: 'AI生成的产品描述已添加到参数字段',
          type: 'success'
        })
      }
      // AITask组件会自动关闭对话框，不需要手动关闭
    },
    handleEditRow(row) {
      if (row.id) {
        this.$confirm('确定修改产品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //
          row.table_name = 'CRMQuoteProduct'
          ModifyQuoteProduct(row.id, row).then(res => {
            this.$message.success('修改成功')
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      }
    },
    handleDeleteFromList(row) {
      // 如果产品已经存在于数据库中，需要调用删除接口
      if (row.id) {
        this.$confirm('确定删除该产品吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 调用删除接口
          Delete(row.id, { table_name: 'CRMQuoteProduct' }).then(res => {
            this.selected = this.selected.filter(item => item.sku !== row.sku)
            this.$message.success('删除成功')
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      } else {
        this.selected = this.selected.filter(item => item.sku !== row.sku)
      }
    },
    close() {
      // 关闭 Drawer 时，清空已选产品列表
      this.$emit('close')
    },
    showImageProcessDialog() {
      this.imageProcessDialogVisible = true
    },
    handleCloseImageProcessDialog() {
      this.imageProcessDialogVisible = false
      this.imageProcessForm = {
        remove_bg: true,
        remove_watermark: false,
        add_watermark: true,
        process_type: 'all',
        watermark_mask: null,
        watermark_mask_url: null
      }
      this.watermarkMaskPreview = null
    },
    handleWatermarkMaskUpload(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        this.imageProcessForm.watermark_mask = e.target.result
        this.watermarkMaskPreview = e.target.result
      }
      reader.readAsDataURL(file)
      return false // 阻止默认上传行为
    },
    handleImageProcess() {
      this.imageProcessing = true

      // 验证处理选项
      if (!this.imageProcessForm.remove_bg && !this.imageProcessForm.remove_watermark) {
        this.$message.error('请至少选择一个处理选项：抠图去背景或去水印')
        this.imageProcessing = false
        return
      }

      // 准备请求参数
      const requestData = {
        remove_bg: this.imageProcessForm.remove_bg,
        remove_watermark: this.imageProcessForm.remove_watermark,
        add_watermark: this.imageProcessForm.add_watermark
      }

      // 添加去水印蒙版（如果有）
      if (this.imageProcessForm.remove_watermark && this.imageProcessForm.watermark_mask) {
        requestData.watermark_mask = this.imageProcessForm.watermark_mask
      }

      // 根据处理范围设置参数
      if (this.imageProcessForm.process_type === 'selected') {
        // 获取选中的产品
        const selectedRows = this.$refs.dragTable.selection
        if (!selectedRows || selectedRows.length === 0) {
          this.$message.error('请先选择要处理的产品')
          this.imageProcessing = false
          return
        }

        // 只处理有ID的产品（已保存的产品）
        const productIds = selectedRows.filter(row => row.id).map(row => row.id)
        if (productIds.length === 0) {
          this.$message.error('选中的产品中没有已保存的产品，请先保存产品')
          this.imageProcessing = false
          return
        }

        requestData.product_ids = productIds
      } else {
        // 处理整个报价单
        if (!this.quote_id) {
          this.$message.error('报价单ID不存在，请先保存报价单')
          this.imageProcessing = false
          return
        }
        requestData.quote_id = this.quote_id
      }

      // 调用API进行图片处理
      ProcessImages(requestData)
        .then(response => {
          if (response.success) {
            this.$message.success(response.msg)

            // 显示处理结果详情
            if (response.data.processed && response.data.processed.length > 0) {
              const processedInfo = response.data.processed.map(item =>
                `产品 ${item.sku}: 处理成功`
              ).join('\n')

              this.$alert(processedInfo, '处理结果', {
                confirmButtonText: '确定',
                type: 'success'
              })
            }

            // 显示失败的处理结果
            if (response.data.failed && response.data.failed.length > 0) {
              const failedInfo = response.data.failed.map(item =>
                `产品 ${item.sku}: ${item.error}`
              ).join('\n')

              this.$alert(failedInfo, '处理失败', {
                confirmButtonText: '确定',
                type: 'warning'
              })
            }

            // 重新加载产品数据以显示更新后的图片
            if (this.quote_id) {
              this.handleGetQuoteProduct()
            }

            // 关闭对话框
            this.imageProcessDialogVisible = false
          } else {
            this.$message.error('图片处理失败：' + response.msg)
          }
        })
        .catch(error => {
          this.$message.error('图片处理失败：' + (error.response && error.response.data && error.response.data.msg ? error.response.data.msg : error.message))
        })
        .finally(() => {
          this.imageProcessing = false
        })
    },
    handleBatchRemove() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要移除的产品')
        return
      }

      this.$confirm(`确定移除选中的 ${this.selectedRows.length} 个产品吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 分离已保存的产品（有id）和未保存的产品（无id）
        const savedProducts = this.selectedRows.filter(row => row.id)
        // const unsavedProducts = this.selectedRows.filter(row => !row.id);

        // 如果有已保存的产品，需要调用删除API
        if (savedProducts.length > 0) {
          // 创建删除Promise数组
          const deletePromises = savedProducts.map(product => {
            return Delete(product.id, { table_name: 'CRMQuoteProduct' })
          })

          // 执行所有删除操作
          Promise.all(deletePromises)
            .then(() => {
              // 从列表中移除所有选中的产品（包括已保存和未保存的）
              const removedCount = this.selectedRows.length
              this.selectedRows.forEach(row => {
                this.selected = this.selected.filter(item => item.sku !== row.sku)
              })

              // 清空选中状态
              this.selectedRows = []
              this.$refs.dragTable.clearSelection()

              this.$message.success(`成功移除 ${removedCount} 个产品`)
            })
            .catch(error => {
              this.$message.error('批量删除失败：' + (error.message || '未知错误'))
            })
        } else {
          // 如果都是未保存的产品，直接从列表中移除
          this.selectedRows.forEach(row => {
            this.selected = this.selected.filter(item => item.sku !== row.sku)
          })

          const removedCount = this.selectedRows.length
          // 清空选中状态
          this.selectedRows = []
          this.$refs.dragTable.clearSelection()

          this.$message.success(`成功移除 ${removedCount} 个产品`)
        }
      }).catch(() => {
        this.$message.info('已取消移除')
      })
    },
    handleSelectionChange(selection) {
      this.selectedRows = selection
    }
  }
}
</script>

